import React, { useRef, useState } from 'react';
import { Button, Card, message, Modal, Progress, Space } from 'antd';
// import { SoundRecordInfo } from "schema/SoundLibrary";
// import { uploadSoundRecord } from "servers/servers";
import Recorder from 'js-audio-recorder';
import { PauseCircleOutlined, PlayCircleOutlined } from '@ant-design/icons';

type IProps = {
  loading: boolean;
  fileId: number;
  disabled?: boolean;
  callback: (file: any) => void;
};

/**UI控件:在线录音-保存录音 */
const OnlineSoundRecord: React.FC<IProps> = ({ loading, fileId, disabled, callback }) => {
  const [recordStep, setRecordStep] = useState<number>(1); // 录音步骤
  const [visible, setVisible] = useState<boolean>(false);
  const [play, setPlay] = useState<number>(0); // 是否播放中，默认为false
  const [duration, setDuration] = useState<number>(0); // 录音时长
  const [playTime, setPlayTime] = useState<number>(0); // 录音播放时长
  const [percent, setPercent] = useState<number>(0); // 录音播放百分比
  const timer = useRef<any>(null); // 计时器存储
  const recorder = useRef<any>(null); // 存储录音对象
  /**打开 */
  const open = () => {
    setVisible(true);
  };

  /**录音 */
  const handleRecord = () => {
    console.log('点击-开始录音,录音实例', recorder.current);
    setRecordStep(2);
    console.log('*******************新建录音实例-6.21');
    // 录音实例化
    recorder.current = new Recorder({
      // type: "wav", //此处的type类型是可修改的
      sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
      sampleRate: 8000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
      numChannels: 1, // 声道，支持 1 或 2， 默认是1
      compiling: false, // (0.x版本中生效,1.x增加中) 是否边录边转换，默认是false
    });
    recorder.current.start().then(
      () => {
        message.success('开始录音');
      },
      (error: any) => {
        // 出错了
        console.log(`${error.name} : ${error.message}`);
      }
    );
    // 回调-录音过程-持续输出时长
    recorder.current.onprogress = (params: any) => {
      // eslint-disable-next-line prefer-const
      let { duration, fileSize } = params;
      // console.log("录音时长(秒)", duration);
      // console.log("录音大小(字节)", fileSize);
      if (duration >= 10 * 60) {
        message.warning('录音时长最大为10分钟，已完成录音');
        recorder.current.stop();
      }
      if (fileSize >= 50 * 1024 * 1024) {
        message.warning('录音文件最大为50M，已完成录音');
        recorder.current.stop();
      }
      duration = duration.toFixed(2);
      setDuration(duration);
    };
    // 回调-录音开始播放
    recorder.current.onplay = () => {
      console.log('onplay');
      setPlay(1);
      setPlayTime(0);
      setPercent(0);
    };
    // 回调-录音播放暂停
    recorder.current.onpauseplay = () => {
      console.log('onpauseplay');
      setPlay(2);
    };
    // 回调-录音恢复播放
    recorder.current.onresumeplay = () => {
      console.log('onresumeplay');
      setPlay(1);
    };
    // 回调-录音播放停止
    recorder.current.onstopplay = () => {
      console.log('onstopplay');
      setPlay(0);
      setRecordStep(1);
      setDuration(0);
      setPlayTime(0);
      setPercent(0);
    };
    // 回调-录音播放完毕
    recorder.current.onplayend = () => {
      console.log('onplayend');
    };
  };
  const handleRecordDone = () => {
    message.success('录音完成');
    console.log('录音总时长', recorder.current.duration);
    recorder.current.stop();
    setRecordStep(3);
  };

  const timeCount = () => {
    // 计时器开始
    // playTime已播放时间
    // debugger;
    let time = playTime;
    if (play === 0) {
      // 点击开始，时间从0开始
      time = 0;
    }
    clearInterval(timer.current);
    timer.current = setInterval(() => {
      time = time + 1;
      const per = Math.round((time * 100) / duration);
      if (per >= 100) {
        message.success('播放结束');
        setPercent(100);
        setPlayTime(duration);
        setPlay(0);
        clearInterval(timer.current);
        return;
      }
      console.log('计时器-当前', time, duration);
      console.log('总长，百分比', duration, per);
      setPercent(per);
      setPlayTime(time);
    }, 1000); //单位：ms
  };

  const handlePlay = () => {
    // 录音播放
    recorder.current.play();
    message.success('开始播放');
    timeCount();
  };

  const handlePause = () => {
    // 播放暂停
    if (play === 1) {
      message.success('暂停播放');
      clearInterval(timer.current);
      recorder.current.pausePlay();
    }
    if (play === 2) {
      message.success('继续播放');
      recorder.current.resumePlay();
      timeCount();
    }
  };
  const handleReset = () => {
    // 重录
    console.log('点击-重录，录音停止，播放停止');
    recorder.current.stop();
    recorder.current.stopPlay();
    clearInterval(timer.current);
    // 销毁录音实例，释放资源，fn为回调函数，
    recorder.current.destroy().then(function () {
      console.log('********重录*****录音实例销毁');
      recorder.current = null;
    });
  };
  const handleClose = () => {
    // 关闭
    console.log('点击-关闭');
    if (recorder.current) {
      console.log('录音停止，播放停止');
      // 判断是否存在;1.未点击开始录音没有实例，2.重录按钮点击时没有实例
      recorder.current.stop();
      recorder.current.stopPlay();
      clearInterval(timer.current);
      // 销毁录音实例，释放资源，fn为回调函数，
      recorder.current.destroy().then(function () {
        console.log('************关闭*************录音实例销毁');
        recorder.current = null;
      });
    }
    // 恢复默认
    setVisible(false);
  };
  /**
   * 时间处理函数
   * 返回例如 00:04 的时间格式
   * num:秒，如3.54s
   */
  const timeFormate = (num: number): string => {
    // 秒
    const seconds = Math.ceil(num);
    const min = Math.floor(seconds / 60);
    const minStr = min < 10 ? '0' + min : min + '';

    const second = seconds % 60;
    const secondStr = second < 10 ? '0' + second : second + '';

    return `${minStr}:${secondStr}`;
  };

  const handleOK = () => {
    // 保存录音文件
    const recorderBlob = recorder.current.getWAVBlob();
    console.log('保存录音-blob流', recorderBlob);
    const uploadFile = new File([recorderBlob], '在线录音文件.wav', {
      type: recorderBlob.type,
    });
    // 进行下一步：上传文件
    callback(uploadFile);
    // 关闭弹窗
    handleClose();
  };

  return (
    <>
      <Button
        style={{ marginLeft: 10 }}
        type="primary"
        loading={loading}
        disabled={disabled}
        onClick={() => {
          console.log('打开在线录制弹窗');
          open();
        }}
      >
        在线录制
      </Button>
      <Modal
        width={600}
        title="在线录音"
        visible={visible}
        onOk={handleOK}
        onCancel={handleClose}
        footer={null}
      >
        <div className="sound-record-title"></div>
        <div className="sound-record-box">
          <Card
            size="small"
            // title="录音"
            style={{ marginTop: 10, width: '100%' }}
          >
            {/* step1：录音 or 取消 */}
            {recordStep === 1 && (
              <>
                {/* 显示录音时长 */}
                <div className="time-count">{timeFormate(duration)}</div>
                <Space className="btn-wrap step1">
                  <Button type="primary" onClick={handleRecord}>
                    开始录音
                  </Button>
                  <Button onClick={handleClose}>取消</Button>
                </Space>
              </>
            )}
            {/* step2：录音完成 or 重录回第一步 */}
            {recordStep === 2 && (
              <>
                {/* 显示录音时长 */}
                <div className="time-count">{timeFormate(duration)}</div>
                <Space className="btn-wrap step2">
                  <Button type="primary" onClick={handleRecordDone}>
                    录音完成
                  </Button>
                  <Button onClick={handleReset}>重录</Button>
                </Space>
              </>
            )}
            {/* step3：展示播放按钮，保存按钮 or 重录回第一步 */}
            {recordStep === 3 && (
              <>
                {/* 显示录音播放 */}
                <div className="audio-wrap">
                  <div className="playline">
                    <Progress percent={percent} size="small" />
                    <div className="time">
                      <span>{timeFormate(playTime)}</span>
                      <span>{timeFormate(duration)}</span>
                    </div>
                  </div>
                  {play ? (
                    // 播放中
                    <Button
                      type="link"
                      icon={<PauseCircleOutlined style={{ fontSize: 38 }} />}
                      onClick={handlePause}
                    ></Button>
                  ) : (
                    // 播放前
                    <Button
                      type="link"
                      icon={<PlayCircleOutlined style={{ fontSize: 38 }} />}
                      onClick={handlePlay}
                    ></Button>
                  )}
                </div>
                <Space className="btn-wrap step3">
                  <Button type="primary" onClick={handleOK}>
                    保存录音
                  </Button>
                  <Button onClick={handleReset}>重录</Button>
                </Space>
              </>
            )}
          </Card>
        </div>
      </Modal>
    </>
  );
};

export default OnlineSoundRecord;
